/*
 * @Description:
 * @Author: LiBin
 * @Date: 2020-11-09 15:12:56
 * @LastEditors: helei
 * @LastEditTime: 2021-06-15 14:53:39
 */
import axios from "axios";
import Qs from "qs";
import { get_data, clear_data } from "./utils";
import { Message } from 'element-ui';

//中断请求
let cancel;
let cancelAjaxText = "中断成功";

let config = {
  method: "post",
  baseURL: "https://smart4.jiandanst.com",
  // baseURL: "http://3r9989u617.qicp.vip/",
  timeout: 600 * 1000,
  transformRequest: [
    (data) => {
      if (data instanceof FormData) {
        return data;
      }
      if (data) {
        return JSON.stringify(data);
      } else {
        return Qs.stringify(data);
      }
    },
  ],
};
var http = axios.create(config);

http.interceptors.request.use(
  (config) => {
    // 请求头里面添加Token
    if (config.data) {
      config.headers["Content-Type"] = "application/json";
    }
    const token = get_data("token");
    if (token && token != "undefined" && token != "null") {
      config.headers["AUTH-TOKEN"] = token;
    }
    return config;
  },
  () => {
    return config;
  }
);

http.interceptors.response.use(
  (res) => {
    console.log(res);
    if (res.data && res.data.code == 804) {
      clear_data("token");
      if (window.location.href.indexOf("/login") === -1) {
        window.location.href = location.href.split("#")[0] + "#/login";
      }
      return Promise.reject(res);
    }
    if (res.data && res.data.code == 400) {
      if(res.data.msg != "NOTPAY"){
        Message({
          type: "error",
          message: res.data.msg
        })
      }
      return Promise.reject(res);
    }
    return Promise.resolve(res.data);
  },
  (error) => {
    if (error && error.response && error.response.status == 804) {
      clear_data("token");
      if (window.location.href.indexOf("/login") === -1) {
        window.location.href = location.href.split("#")[0] + "#/login";
      }
      return;
    }

    if (axios.isCancel(error)) {
      return;
    }
    // Toast("加载失败~");
    return Promise.reject(error);
  }
);

//接口列表
export default {
  fetch: (url, config = {}) => {
    console.log("+-----");
    console.log(config);
    return new Promise((resolve, reject) => {
      http(url, config)
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  },
  stop: () => {
    if (cancel) {
      cancel(cancelAjaxText); //切换页面强行中断请求 router.beforeEach中用到
    }
  },
};
